package com.study.jyg.rxjava2study.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.study.jyg.rxjava2study.R;
import com.study.jyg.rxjava2study.base.BasicActivity;
import com.study.jyg.rxjava2study.utils.AdapterInit;
import com.study.jyg.rxjava2study.utils.ToastUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class BluetoothClientActivity extends BasicActivity {

    private List<String> bluetoothDevices = new ArrayList<String>();
    private final UUID MY_UUID = UUID
            .fromString("abcd1234-ab12-ab12-ab12-abcdef123456");//随便定义一个
    private BluetoothSocket clientSocket;
    private BluetoothDevice device;
    private OutputStream os;//输出流

    private BluetoothReceiver receiver;
    private BluetoothAdapter mBluetoothAdapter;

    private BaseQuickAdapter<String, BaseViewHolder> adapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_bluetooth_client;
    }

    @Override
    protected void initView() {
        initAdapter();
        findViewById(R.id.btnSearch).setOnClickListener(v -> {
            if (mBluetoothAdapter != null){
                //支持蓝牙模块儿
                if (!mBluetoothAdapter.isEnabled()){
                    ToastUtils.show("请打开蓝牙！！");
                    return;
                }
                //获取已经配对的蓝牙设备
                //如果当前在搜索，就先取消搜索
                if (mBluetoothAdapter.isDiscovering()) {
                    mBluetoothAdapter.cancelDiscovery();
                }
                //开启搜索
                mBluetoothAdapter.startDiscovery();
            }
        });
    }

    private void initAdapter() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                bluetoothDevices.add(device.getName() + ":" + device.getAddress());
            }
        }
        adapter = AdapterInit.initRecyclerView(findViewById(R.id.recyclerView), R.layout.item_bluetooth, new LinearLayoutManager(mContext), (helper, item) -> {
            helper.setText(R.id.tvItem, item);
        }, (adapter1, view, position) -> {

        });
        adapter.setNewData(bluetoothDevices);

        receiver = new BluetoothReceiver();
        IntentFilter filter = new IntentFilter();
        //每搜索到一个设备就会发送一个该广播
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        //当全部搜索完后发送该广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //设置优先级
        filter.setPriority(Integer.MAX_VALUE);
        this.registerReceiver(receiver, filter);
    }

    /**
     * 链接设备
     * @param device
     * @throws IOException
     */
    private void connect(BluetoothDevice device) throws IOException {
        // 固定的UUID
        final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
        UUID uuid = UUID.fromString(SPP_UUID);
        BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
        socket.connect();
    }

    /**
     *  * 定义广播接收器
     *  
     */
    class BluetoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    bluetoothDevices.add(device.getName() + ":" + device.getAddress());
                    adapter.notifyDataSetChanged();
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //已搜素完成
            }
        }
    }


}